﻿using System;
using System.IO;
using System.Web;
using DeluxeSources.Practices.ObjectContracts;

namespace DeluxeSources.Practices.Handlers
{
    /// <summary>
    /// UploadActionHandler 的摘要说明
    /// </summary>
    public class UploadActionHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            string uploadActionId = string.Format("{0}-{1}", Guid.NewGuid(), DateTime.Now.GetHashCode().ToString("X"));
            this.SaveToTemporaryFolder(context.Request, uploadActionId);
            context.Response.Redirect(string.Format("~/WebPages/TraceListenerPage.aspx?actionId={0}", uploadActionId));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region SaveToTemporaryFolder
        /// <summary>
        /// 保存文件到临时目录。
        /// </summary>
        /// <param name="request"><see cref="HttpRequest"/>对象实例</param>
        /// <param name="actionId">上传动作唯一标识。</param>
        private void SaveToTemporaryFolder(HttpRequest request, string actionId)
        {
            if (!object.ReferenceEquals(request.Files, null) && request.Files.Count > 0)
            {
                TemporaryDirectory directory = new TemporaryDirectory();
                if (!directory.BaseDirectory.Exists) directory.BaseDirectory.Create();
                request.Files[0].SaveAs(Path.Combine(directory.BaseDirectory.FullName, actionId) + ".xls");
            }
        }
        #endregion
    }
}